<template>
    <div class="users">
      <!-- 导航面包屑 -->
       <separator class="separator-users" :nameList='newNameList'></separator>
       <!-- card卡片 -->
       <el-card class="box-card">
         <!-- 搜索部分 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input placeholder="请输入内容"  
                        class="input-with-select" 
                        v-model="queryIonfo.query" 
                        clearable
                        @clear='getUsersList(queryIonfo)'
                        >
                 <el-button slot="append" icon="el-icon-search" @click="getUsersList(queryIonfo)"></el-button>
              </el-input>
            </el-col>
             <el-col :span="4">
                <el-button type="primary" @click=" isDialogVisible = true">添加用户</el-button>
             </el-col>
          </el-row>
           <!-- table 表格渲染数据 -->
          <el-table :data="userList" border stripe>
             <el-table-column type="index"></el-table-column>
            <el-table-column prop="username" label="姓名"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="mobile" label="电话"></el-table-column>
            <el-table-column prop="role_name" label="角色"></el-table-column>
            <el-table-column prop="mg_state" label="状态" width='100px'>
              <template slot-scope="scope">
                 <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="" label="操作" width="180px">
              <template slot-scope="scope">
                 <el-button type="primary" icon="el-icon-edit" size='mini' @click="editorDialogList(scope.row.id)"></el-button>
                 <el-button type="danger" icon="el-icon-delete" size='mini' @click="delUsers(scope.row.id)"></el-button>
                 <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable='false'>
                   <el-button type="warning" icon="el-icon-orange" size='mini'  @click="usersRoles(scope.row)"></el-button>
                 </el-tooltip>  
              </template>
            </el-table-column>
          </el-table>
          <!-- 页面分页效果 -->
          <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryIonfo.pagenum"
                :page-sizes="[8,20,30, 40, 50]"
                :page-size="queryIonfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
          </el-pagination>
       </el-card>
       <dialog-main :title="queryIonfo.title" 
                    :dialogWidths='50' 
                    :showDialogVisible='isDialogVisible' 
                    @cancelDialogVisible='cancelDialogVisible'
                    @sureDialogVisible='sureDialogVisible'
                    @closeDialog="closeDialogBox"
                    >
         <div slot="contentList">
            <div>
              <el-form ref="addFormRef" :model="addForm" :rules="addFormRoles" label-width="80px">
                <el-form-item label="用户名称" prop='userName'>
                  <el-input v-model="addForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop='password'>
                  <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop='mobile'>
                  <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop='email'>
                  <el-input v-model="addForm.email"></el-input>
                </el-form-item>
            </el-form>
          </div>
         </div>
       </dialog-main>
       <!-- 修改用户列表 -->
       <el-dialog title="修改用户信息" :visible.sync="editorDialogVisible" width="50%"  :close-on-click-modal='false'>
         <div class="editorBox">
            <el-form ref="editorFormRef" :model="editorForm" :rules="editorFormRoles" label-width="80px">
                <el-form-item label="用户名称">
                  <el-input  v-model="editorForm.username" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop='mobile'>
                  <el-input v-model="editorForm.mobile"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop='email'>
                  <el-input v-model="editorForm.email"></el-input>
                </el-form-item>
            </el-form>
         </div>
         <span slot="footer" class="dialog-footer">
           <el-button @click="editorCancelDialog">取 消</el-button>
           <el-button type="primary" @click="editorSureDialog()">确 定</el-button>
         </span>
       </el-dialog>
       <!-- 分配权限会话框 -->
       <el-dialog title="分配权限" :visible.sync="rolesDialogVisible" width="30%" @close="closeRoles">
         <div>
           <p>用户姓名：{{rolesList.username}}</p>
           <p>用户角色：{{rolesList.role_name}}</p>
           <el-select v-model="selectValue" placeholder="请选择">
             <el-option v-for="item in usersRolesAll "
                      :key="item.id"
                      :label="item.roleName"
                      :value="item.id">
             </el-option>
          </el-select>
         </div>
         <span slot="footer" class="dialog-footer">
           <el-button @click="rolesDialogVisible = false">取 消</el-button>
           <el-button type="primary" @click="rolesSureVisible">确 定</el-button>
         </span>
       </el-dialog>
    </div>
</template>>

<script>
  import Separator from 'components/content/separator/Separator'
  import DialogMain from 'components/content/dialogContent/DialogMain'

  import {getUsers,setState,addUsers,editorUsers,setUsers,removeUsers,setUsersRoles,changeUsersRoles} from 'network/users'

  export default {
    name:'Users',
    components:{
      Separator,
      DialogMain  
    },
    data(){
      //定义邮箱的验证规则
      var emailRoles = (rule,value,cb)=>{
      //  邮箱的正则表达式
       const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if(regEmail.test(value)){
          //合法邮箱
          return cb()
        }
        cb(new Error('请输入合法的邮箱'))
      }
      //定义手机号的验证规则
      var mobileRoles = (rule,value,cb)=>{
        //  手机号的正则表达式
        const regPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if(regPhone.test(value)){
          return cb();
        }
        cb(new Error('请输入正确的手机号'))
      }
      return{
        newNameList:['用户管理','用户列表'],
        queryIonfo:{
          title:"添加用户",
          query:'',
          // 当前显示第几页
          pagenum:1,
          //当前每页显示多少条数据
          pagesize:8
        },
        //保存用户列表
        userList:[],
        //总条数
        total:0,
        // 会话框显示隐藏
        isDialogVisible:false,
        //添加用户数据
        addForm:{
          userName:'',
          password:'',
          email:'',
          mobile:''
        },
        //验证表单的规则对象
        addFormRoles:{
          userName:[
            {required:true,message:'请输入用户名称',trigger:'blur'},
            {min:3,max:6,message:'用户名长度在3到6个字符之间', trigger:'blur'}
          ],
          password:[
            {required:true,message:'请输入密码',trigger:'blur'},
            {min:6,max:15,message:'密码长度在6到15个字符之间', trigger:'blur' }
          ],
          email:[
            {required:true,message:'请输入邮箱',trigger:'blur'},
            {validator:emailRoles,trigger:'blur'}
          ],
          mobile:[
            {required:true,message:'请输入电话',trigger:'blur'},
            {validator:mobileRoles,trigger:'blur'}
          ]
        },
        // 编辑用户信息会话框
         editorDialogVisible:false,
        // 根据用户id 保存单个用户的信息
         editorForm:{},
         //编辑用户信息的验证规则
         editorFormRoles:{
           mobile:[
            {required:true,message:'晴输入手机号',trigger:'blur'},
            {validator:mobileRoles,trigger:'blur'}
           ],
           email:[
             {required:true,message:'请输入邮箱',trigger:'blur'},
             {validator:emailRoles,trigger:'blur'}
           ]
         },
        //  权限列表会话框
         rolesDialogVisible:false,
        //  保存权限列表会话框的用户数据
        rolesList:{},
        //保存权限列表的权限数据
        usersRolesAll:{},
        //select value 数据绑定的值
        selectValue:'' 
      }
    },
    created(){
     this.getUsersList(this.queryIonfo);
    },
    methods:{
      // 获取数据列表
      getUsersList(config){
        getUsers(config.query,config.pagenum,config.pagesize).then(res=>{ 
          const data=res.data;
          if(data.meta.status!==200){
            return this.$message.error('data.meta.msg');
          }
          this.userList = data.data.users;
          this.total = data.data.total;
        },err=>{
          console.log(err);
        })
      },
      // 页面显示条数发生改变时
      handleSizeChange(pagesize){
         this.queryIonfo.pagesize = pagesize;
         this.getUsersList(this.queryIonfo);
      },
      // 点击第几页时 出发
      handleCurrentChange(pagenum){
        this.queryIonfo.pagenum = pagenum;
        this.getUsersList(this.queryIonfo);
      },
      //更改状态
      changeState(change){
        // console.log(change);
        setState(change.id,change.mg_state).then(res=>{
          if(res.data.meta.status !==200){
            return this.$message.error('更新状态失败');
            change.mg_state=!change.mg_state
          }
          this.$message.success('更新状态成功');
          console.log(res);
        },err=>{
          console.log(err);
        })
      },
      // 会话框取消按钮
      cancelDialogVisible(){
        this.isDialogVisible=false
      },
      // 会话框确定按钮
      sureDialogVisible(){
        //验证表单数据是否通过规则验证
        this.$refs.addFormRef.validate(vali => {
          if(!vali){
            return false
          }
          //向后台添加用户信息
          addUsers(this.addForm.userName,this.addForm.password,this.addForm.email,this.addForm.mobile).then(res=>{
            console.log(res);
            if(res.data.meta.status===400){
               return this.$message.error('用户名已存在');
            } else if(res.data.meta.status===201){
              //隐藏会话框
               this.isDialogVisible=false;
              //刷新用户列表
               this.getUsersList(this.queryIonfo);
               return this.$message.success('用户添加成功');
            }
          },err=>{
            console.log(err);
          })
        });
       
      },
      // 会话框关闭后触发的方法
      closeDialogBox(){
        this.$refs.addFormRef.resetFields();
      },
      // 编辑用户信息
      editorDialogList(id){
        this.editorDialogVisible = true;
        editorUsers(id).then(res=>{
          this.editorForm=res.data.data;
          console.log(this.editorForm);
        },err=>{
          console.log(err);
        })
      },
      //编辑用户信息 会话框 确定按钮
      editorSureDialog(){
        this.$refs.editorFormRef.validate(vali=>{
          if(!vali){return false }
          //向数据库返回修改结果
          setUsers(this.editorForm.id,this.editorForm.email,this.editorForm.mobile).then(res=>{
            console.log(res);
            if(res.data.meta.status!==200){
              return this.$message.error('修改失败');
            }
            this.$message.success('修改成功');
            //刷新用户列表
            this.getUsersList(this.queryIonfo);
            //关闭弹框
            this.editorDialogVisible = false;
          },err=>{
            console.log(err);
          })
        })
      },
      editorCancelDialog(){
        this.$refs.editorFormRef.idresetFields();
        this.editorDialogVisible = false;
      },
      //删除用户
      delUsers(id){
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              removeUsers(id).then(res=>{
                console.log(res.data.meta.status);
                if(res.data.meta.status!==200){
                   return this.$message.error('删除失败');
                }
                 //刷新用户列表
                 this.getUsersList(this.queryIonfo);
                 this.$message({
                 type: 'success',
                 message: '删除成功!'
              });
              },err=>{
                console.log(err);
              })
             
            }).catch(() => {
              this.$message({type: 'info', message: '已取消删除'   });          
            });
      },
      //分配权限
      usersRoles(userInfo){
        this.rolesList=userInfo;
        setUsersRoles().then(res=>{
          if(res.data.meta.status!==200){
            return this.$message.error('权限获取失败');
          }
          this.usersRolesAll=res.data.data;
          console.log(this.rolesList);
        },err=>{
          console.log(err);
        })
        this.rolesDialogVisible=true;
      },
      //为用户分配权限会话框 确定按钮
      rolesSureVisible(){
        if(!this.selectValue){
          return this.$message.error('请选择权限名称');
        }
        changeUsersRoles(this.rolesList.id,this.selectValue).then(res=>{
          if(res.data.meta.status!==200){
            return this.$message.error('更新角色失败');
          }
         this.$message.success('更新角色成功');
         console.log(res);
         //更新数据列表
         this.getUsersList(this.queryIonfo);
         this.rolesDialogVisible=false;
        },err=>{
          console.log(err);
        })
      },
      //监听分配权限会话框的关闭事件
      closeRoles(){
        console.log(11111);
        this.selectValue='',
        this.rolesList={}
      }
    }
  }
</script>>

<style lang="less">
  .el-table{
    margin-top: 15px;
  }
  .el-pagination{
    margin-top: 15px;
  }
</style>>